package com.bw.controller;

import com.bw.entity.House;
import com.bw.entity.HouseAdd;
import com.bw.entity.HouseQuery;
import com.bw.entity.Region;
import com.bw.mapper.HouseMapper;
import com.bw.service.HouseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.spring.kun.common.UploadPicUtils;
import org.spring.kun.common.ZzyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@Controller
public class HouseController {

    @Autowired
    HouseMapper houseMapper;
    @Autowired
    HouseService houseService;


    @RequestMapping("/list.do")
    public String list(HouseQuery query, Integer pageNum, Model model){
        //1.下拉框
       List<Region> provinceList =  houseMapper.selectProvince();
       model.addAttribute("provinceList",provinceList);

       // 2. 分页查询
        PageHelper.startPage(pageNum == null ? 1: pageNum , 3);

        List<House> list = houseMapper.list(query);

        PageInfo<House> pageInfo = new PageInfo<>(list);
        model.addAttribute("pageInfo",pageInfo);
        return  "list";
    }


    @RequestMapping("/selectCity.do")
    @ResponseBody
    public List<Region> selectCity(Integer provinceId){

      return   houseMapper.selectCity(provinceId);
    }

    @RequestMapping("/addPage.do")
    public String addPage(Model model){

        //1 省份下拉框
        List<Region> provinceList =  houseMapper.selectProvince();
        model.addAttribute("provinceList",provinceList);

      return  "add";
    }

    @RequestMapping("/add.do")
    public String add(@Valid HouseAdd houseAdd, BindingResult result, Model model, HttpServletRequest request){

        if (result.hasErrors()){
            model.addAttribute("error",result.getAllErrors().get(0).getDefaultMessage());
            //1 省份下拉框
            List<Region> provinceList =  houseMapper.selectProvince();
            model.addAttribute("provinceList",provinceList);
            return "add";
        }
        // 保存图片到webapp下 并返回图片的访问地址
        String url = UploadPicUtils.upload(houseAdd.getPicFile(), request);
        houseAdd.setPicUrl(url);

        houseService.add(houseAdd);
        boolean b = ZzyUtils.sendSms("17611221735", System.currentTimeMillis() + "添加了楼盘信息", 5);
        System.out.println(b);
        return  "redirect:list.do";
    }


}
